package cn.e4j.modular.system.controller;

import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.shiro.ShiroKit;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 在线用户控制类
 *
 * @author yuan_rz
 * @Date 2019/12/12 14:45
 */
@Controller
@RequestMapping("/sys/onlineuser")
public class SysOnlineUserController extends BaseController {

    @Autowired
    EnterpriseCacheSessionDAO sessionDao;

    /**
     * 跳转页面
     */
    @RequiresPermissions("sys:onlineuser:init")
    @RequestMapping(value = {"", "init"})
    public String index() {
        return "/pc/system/onlineuser.html";
    }

    /**
     * 查询列表数据
     */
    @RequestMapping("/getListData")
    @RequiresPermissions("sys:onlineuser:init")
    @ResponseBody
    public ResponseData getListData(@DtoParam DtoWapper dtoWapper) {
        Collection<Session> sessionCollection = sessionDao.getActiveSessions();
        List<Dto> sessionList = new ArrayList<>();
        for (Session session : sessionCollection) {
            Dto dto = Dtos.newDto();
            dto.put("ID", session.getId().toString());
            dto.put("USER_NAME", session.getAttribute("username"));
            dto.put("HOST", session.getHost());
            dto.put("LAST_ACCESS_TIME", session.getLastAccessTime());
            dto.put("START_TIMESTAMP", session.getStartTimestamp());
            dto.put("TIME_OUT", session.getTimeout());
            sessionList.add(dto);
        }
        return new SuccessResponseData(sessionList);
    }

    /**
     * 删除数据
     */
    @RequestMapping("/killUser")
    @RequiresPermissions("sys:onlineuser:init")
    @ResponseBody
    public ResponseData killUser(String sessionId) {
        if (ShiroKit.getSession().getId().equals(sessionId)) {
            return new ErrorResponseData("禁止强制下线自己");
        } else {
            sessionDao.delete(sessionDao.readSession(sessionId));
        }
        return SUCCESS_TIP;
    }
}
